#include "convert.h"
std::string convert(std::vector<variable> variables, std::vector<token> tokens) {
    converter cvt(variables, tokens);
    cvt.convert();
    return cvt.get_finalname();
}

converter::converter(std::vector<variable> variables, std::vector<token> tokens):variables(variables), tokens(tokens), finalname("") {}

void converter::convert() {
    for (auto tk : tokens) {
        std::string value = match_var(tk);
        finalname += value;
    }
}
std::string converter::get_finalname() {
    return finalname;
}
std::string converter::match_var(token tk) {
    if(tk.type == tokentype::CONST) {
        return tk.varname;
    }
    for(auto var:variables) {
        if(var.name == tk.varname) {
            switch (var.type) {
                case tokentype::LETTER: case tokentype::WORD:case tokentype::X:
                    return var.get_str_value();
                case tokentype::DIGIT:case tokentype::NUMBER:
                    std::stringstream bufstream;
                    if (var.type == tokentype::NUMBER) {
                        // while(bufstream.str().length() < tk.count) {
                        //     bufstream = std::stringstream('0') << bufstream;
                        // }
                        bufstream<< std::setw(tk.count) << std::setfill('0') << var.get_int_value();
                    } else {
                        bufstream << var.get_int_value();
                    }
                    return bufstream.str();
            }
        }
    }
    throw std::string("no such variable") + tk.varname;
}
